package com.infinitus.activity.web;

import com.infinitus.activity.common.ResponseCodeConstant;
import com.infinitus.activity.util.KeyGenerator;
import com.infinitus.activity.util.LoginUtils;
import com.infinitus.activity.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.regex.Pattern;

/**
 * @author: luzhenjie
 * @create: 2019/3/11
 * @desc:
 */
@Controller
@RequestMapping(value = "/sys")
public class LoginController {

    private static Logger logger = Logger.getLogger(LoginController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${deploycolId}")
    private  String deploycolId;

    @Autowired
    private  LoginUtils loginUtils;

    /**
     * @Desc 用户登录
     */
    @RequestMapping(value = "/login" , method = RequestMethod.POST)
    public ResponseEntity<?> login(
            @RequestParam String dealerNo,
            @RequestParam String password,
            @RequestParam(required = false,defaultValue = "0") String staging
    ) {
        /**
         * @Desc 卡号格式合法性校验
         */
        if(!Pattern.matches("^\\d{9}$", dealerNo)) {
            return ResponseEntity.badRequest().body(ResponseCodeConstant.ILLEGAL_DEALERNO);
        }
        //性能测试的标示
//        if ("1".equalsIgnoreCase(staging)){
//            Boolean hasKey = stringRedisTemplate.hasKey(KeyGenerator.getLoginAlready(deploycolId,dealerNo));
//            if (!hasKey) {
//                stringRedisTemplate.opsForValue().set(KeyGenerator.getLoginAlready(deploycolId,dealerNo), "0");
//            }
//            return ResponseEntity.ok().build();
//        }
        try {
            String message = loginUtils.login(dealerNo,password);
            if(StringUtils.isEmpty(message)) {
                Boolean hasKey = stringRedisTemplate.hasKey(KeyGenerator.getLoginAlready(deploycolId,dealerNo));
                if (!hasKey) {
                    stringRedisTemplate.opsForValue().set(KeyGenerator.getLoginAlready(deploycolId,dealerNo), "0");
                }
                return ResponseEntity.ok().build();
            }else{
                return ResponseEntity.badRequest().body(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e);
        }

    }

}